<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>数据源信息新增</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${ctx}/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="${ctx}/systemStatic/style/admin.css">
    <link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>
    <link rel="stylesheet" href="${ctx}/css/public.css">
    <script type="text/javascript">
        var __ctx = "${ctx}";
    </script>
    <link rel="stylesheet" href="${ctx}/css/form.css">
</head>
<body>

<form class="layui-form" style="background: #fff;height: 100%;">
    <div class="layui-fluid dataSourceAdd" style="height:380px;overflow: auto">
    <div class="layui-form-item item-first">
        <label class="layui-form-label">名称<span style="color:red;">*</span></label>
        <div class="layui-input-block" >
            <input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入名称"
                   class="layui-input" maxlength="32">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">别名<span style="color:red;">*</span></label>
        <div class="layui-input-block">
            <input type="text" id="alias" name="alias" lay-verify="required" placeholder="请输入别名" autocomplete="off"
                   class="layui-input" maxlength="32">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">数据源类型<span style="color:red;">*</span></label>
        <div class="layui-input-block">
            <select name="dbType" lay-filter="dbType" lay-verify="required">
                <option value="">请选择</option>
                <option value="mysql">mysql</option>
                <option value="oracle">oracle</option>
                <option value="mssql">mssql</option>
                <option value="gbase">gbase</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">初始化容器</label>
        <div class="layui-input-block">
            <select lay-filter="aihao" name="enabled">
                <option value="false">否</option>
                <option value="true">是</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">是否生效</label>
        <div class="layui-input-block">
            <select lay-filter="aihao" name="initOnStart">
                <option value="false">否</option>
                <option value="true">是</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">数据源模板<span style="color:red;">*</span></label>
        <div class="layui-input-block">
            <select name="dataSourceDef" lay-filter="dataSourceDef" id="dataSourceDef" lay-verify="required">
                <option value=""></option>
            </select>
        </div>
    </div>
    <div class="clear">
    </div>
    </div>
    <div class="layui-btn-container" style="position: absolute;left: 30%;bottom: 0;">
        <button class="layui-btn" type="button" id="testConn">测试连接</button>
        <button class="layui-btn" lay-submit lay-filter="dataSourceForm">保存</button>
        <button class="layui-btn layui-btn-danger" id="return">取消</button>
    </div>
</form>
<script src="${ctx}/public/component.js" type="text/javascript"></script>
<script src="${ctx}/layui/layui.js"></script>
<script>
    var def;
    var settingJsons;
    var dataSourceDefs;
    var dbTypeList = [{
        value: "mysql",
        driverClassName: "com.mysql.jdbc.Driver",
        url: "jdbc:mysql://主机:3306/数据库名?useUnicode=true&characterEncoding=utf-8"
    }, {
        value: "oracle",
        driverClassName: "oracle.jdbc.OracleDriver",
        url: "jdbc:oracle:thin:@主机:1521:数据库实例"
    }, {
        value: "mssql",
        driverClassName: "com.microsoft.sqlserver.jdbc.SQLServerDriver",
        url: "jdbc:sqlserver://主机:1433;databaseName=数据库名;"
    },{
        value: "gbase",
        driverClassName: "com.gbase.jdbc.Driver",
        url: "jdbc:gbase://主机:5258/数据库名"
    }];
    var setter;

    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','form',  'jquery', 'element','common'], function () {
        var form = layui.form;
            var layer = layui.layer;
        var $ = layui.$;
        var setter = layui.setter;
        var common = layui.common;
        form.on('select(dataSourceDef)', function (data) {
            var value = data.value;
            for (var k = 0; k < dataSourceDefs.length; k++) {
                if (dataSourceDefs[k].id == value) {
                    def = dataSourceDefs[k];
                    settingJsons = dataSourceDefs[k].settingJson;
                    changeDef(settingJsons);
                    changeDbType();
                }
            }
        });

        //关闭弹窗
        $('#return').click(function () {
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        });

        /*鼠标失去焦点将内容自动填充到别名*/
        $("input[name='name']").change(function () {
            var str = $(this).val();
            if (str == "") return;
            var arrRslt = component.chineseToPinyinAlias(str);
            $("#alias").val(arrRslt[0]);
        });

        /*监听下拉值得改变*/
        form.on("select(dbType)", function () {
            changeDbType();
        });

        //监听提交
        form.on('submit(dataSourceForm)', function (data) {
            var settingJson = processSettingJson();
            data.field["settingJson"] = JSON.stringify(settingJson);
            data.field["classPath"] = def.classPath;
            data.field["initMethod"] = def.initMethod;
            data.field["closeMethod"] = def.closeMethod;
            $.ajax({
                url: serverPath.systemPath + setter.sysLinkPath + "dataSource/add",
                type: "POST",
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(data.field),
                success: function (result) {
                    if (common.filterRecord(result)) {
                        window.parent.layer.alert(result.msg, function (index) {
                            parent.layer.close(index);
                            parent.layui.table.reload('dataSource');
                            parent.layui.totalFilter.init('dataSource');
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                        });
                    } else {
                        window.parent.layer.alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("保存失败！" + XMLHttpRequest.status);
                }
            });
            return false;
        });

        $.ajax({
            type: 'post',
            dataType: 'json',
            url: serverPath.systemPath + setter.sysLinkPath + "dataSourceDef/list",
            success: function (result) {
                dataSourceDefs = result.data;
                $.each(result.data, function (index, objVal) {
                    $("#dataSourceDef").append("<option value=" + objVal.id + ">" + objVal.name + "</option>");
                });
                form.render();
            }
        });
        /*测试连接*/
        $("#testConn").click(function () {
            var json = {};
            json["name"] = $("input[name='name']").val();
            json["alias"] = $("input[name='alias']").val();
            var classPath = "org.apache.commons.dbcp.BasicDataSource";
            json["classPath"] = classPath;
            json["dbType"] = $("select[name='dbType']").val();
            json["enabled"] = $("select[name='enabled']").val();
            json["initOnStart"] = $("select[name='initOnStart']").val();

            if (settingJsons == '' || settingJsons == undefined) {
                layer.alert("请先填写相关连接信息");
                return false;
            }
            var parseJson = JSON.parse(settingJsons);
            for (var i = 0; i < parseJson.length; i++) {
                var name = parseJson[i].name;
                parseJson[i]["value"] = $("input[name='" + name + "']").val()
            }
            json["settingJson"] = JSON.stringify(parseJson);
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: serverPath.systemPath + setter.sysLinkPath + "dataSource/checkConnection",
                data: JSON.stringify(json),
                contentType: 'application/json',
                success: function (result) {
                    layui.layer.alert(result.msg)
                },
                error: function (d) {
                    layui.layer.alert("请求失败")
                }
            });
        });

        function processSettingJson() {
            var jsonArray = JSON.parse(def.settingJson);
            var parse = JSON.parse(settingJsons);
            for (var i = 0; i < jsonArray.length; i++) {
                for (var j = 0; j < parse.length; j++) {
                    if (jsonArray[i].name == parse[j].name) {
                        jsonArray[i]["value"] = $("input[name='" + jsonArray[i].name + "']").val();
                    }
                }
            }
            return jsonArray;
        }
        /*数据源类型改变*/
        function changeDbType() {
            var dbType = $("select[name='dbType']").val();
            if (dbType && $("select[name='dataSourceDef']").val()) {
                for (var i = 0; i < dbTypeList.length; i++) {
                    if (dbType === dbTypeList[i].value) {
                        $("input[name='driverClassName']").val(dbTypeList[i].driverClassName);
                        $("input[name='url']").val(dbTypeList[i].url);
                    }
                }
            }
        };
        function changeDef(settingJson) {
            var s = JSON.parse(settingJson);
            $(".clear").html("")
            for (var j = 0; j < s.length; j++) {
                //是否必填
                var baseAttr = s[j].baseAttr;
                var inputStr = '<input type="text" name="' + s[j].name + '" placeholder="请输入' + s[j].comment + '" autocompvare="off" class="layui-input">';
                if(baseAttr == "true"){
                    inputStr = '<input type="text" name="' + s[j].name + '" placeholder="请输入' + s[j].comment + '" autocompvare="off" class="layui-input" lay-verify="required">';
                }
                $(".clear").append('<div class="layui-form-item"><label class="layui-form-label" style="overflow: hidden;white-space :nowrap; text-overflow:ellipsis;">' + s[j].comment + '<label style="color: red;">*</label></label>' +
                    '<div class="layui-input-block" style="width:51%;margin-left:0;float: left;">'+inputStr+' </div><div class="layui-form-mid layui-word-aux">(' + s[j].type + ')</div></div>')
            }
        }

    });
</script>
</body>
</html>